package cn.dyp.com.logprint.action;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Element;


import android.content.Context;

import cn.dyp.com.logprint.db.DatabaseUtil;
import cn.dyp.com.logprint.util.Util;

/**
 * @author zongbingwu 用户登录请求处理类,从客户端请求body中取得用户名和密码
 *         然后从检查该用户是否存在，并将结果返回给http服务器或socket服务器
 */
public class LoginAction extends BaseAction {
	// action name
	public static final String TAG = "login";

	private Context context;

	public LoginAction(Context context) {
		this.context = context;
	}

	// jason协议的解析函数
	@Override
	protected String jasonPorcess(String param) {
		JSONObject jsonResponse = new JSONObject();
		try {
			JSONObject jsonRequest = new JSONObject(param);
			// 处理登陆请求
			String username = "";
			String password = "";
			// 解析用户名
			if (jsonRequest.has("username")) {
				username = jsonRequest.getString("username");
				logObj = username;
			}
			// 解析用户密码
			if (jsonRequest.has("password")) {
				password = jsonRequest.getString("password");
			}
			// 通过用户名和密码，验证某个用户是否存在数据库中
			if (DatabaseUtil.query(username, password, context)) {
				jsonResponse.put("result", "ok");
				logMsg = "User login success";
			} else {
				jsonResponse.put("result", "failed");
				logMsg = "User login failed";
			}
			// 返回结果
			return jsonResponse.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// soap协议的解析函数
	@Override
	protected String soapPorcess(String param) {
		String username = "";
		String password = "";

		// 从完整的soap协议内容中解析出soap body内容
		Element soapBodyEle = Util.getSoapBodyElement(param);
		if (soapBodyEle != null) {
			// 解析用户名
			username = Util.getChildElementValueStr(soapBodyEle, "username");
			logObj = username;
			// 解析用户密码
			password = Util.getChildElementValueStr(soapBodyEle, "password");
		}

		String retValue = "failed";
		// 通过用户名和密码，验证某个用户是否存在数据库中
		if (DatabaseUtil.query(username, password, context)) {
			retValue = "ok";
			logMsg = "User login success";
		} else {
			logMsg = "User login failed";
		}
		// 返回结果
		return Util.getSoapXml(Util.getXmlElementStr("result", retValue));
	}

}
